/*
 * @lc app=leetcode.cn id=227 lang=javascript
 *
 * [227] 基本计算器 II
 */

// @lc code=start
/**
 * @param {string} s
 * @return {number}
 */
var calculate = function(s) {
  s = s.trim();
  let stack = [];
  let preSign = '+';
  let num = 0;
  for(let i in s) {
      if (!isNaN(s[i]) && s[i] !== ' ') {
          num = num * 10 + Number(s[i]);
      }
      if (isNaN(s[i]) || i == s.length - 1) {
          switch(preSign) {
              case '+': 
                 stack.push(num);
                 break;
              case '-':
                  stack.push(-num);
                  break;
              case '*':
                  stack.push(stack.pop() * num);
                  break;
              default:
                  stack.push(stack.pop() / num | 0);
                  break;
          }
          num = 0;
          preSign = s[i];
      }
  }
  return stack.reduce((a,b) => a+b);
};
// @lc code=end

